package team.zero.lemon.module.sys.news.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.zero.lemon.common.date.UTC;
import team.zero.lemon.common.exception.CustomException;
import team.zero.lemon.common.security.session.SessionContext;
import team.zero.lemon.common.service.CrudService;
import team.zero.lemon.module.sys.news.dao.INewsDao;
import team.zero.lemon.module.sys.news.entity.News;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by bolin on 2016/11/14.
 */
@Service
public class NewsService extends CrudService<INewsDao, News> {

    @Transactional
    public boolean send(String title, int instanceId, int module, String href, int sendUserId, String sendUserName, List<Integer> userIds) {
        List<News> newses = new ArrayList<News>();
        userIds.forEach(userId -> {
            News news = new News();
            news.setInsert(true);
            news.setTitle(title);
            news.setInstanceId(instanceId);
            news.setModule(module);
            news.setHref(href);
            news.setUserId(userId);
            news.setSendUserId(sendUserId);
            news.setSendUserName(sendUserName);
            news.setStatus(0);
            news.setSendTime(UTC.date());
            news.setInstanceId(instanceId);
        });
        try {
            dao.insert(newses);
            return true;
        } catch (Exception exc) {
            throw new CustomException(exc.getMessage());
        }
    }

    public boolean read(News news) {
        try {
            news.setStatus(1);
            if (news.getUserId() == null) {
                news.setUserId(SessionContext.getSession().getId());
            }
            news.setInsert(false);
            news.preUpdate();
            dao.updateNewStatus(news);
            return true;
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }
}
